local extension = Package("rfenghou_tang")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"
local HQ = require "packages/hanqing/utility/hanqing_util"

Fk:loadTranslationTable{
  ["rfenghou_tang"] = "天唐",
}

local lishimin = General(extension, "rfenghou__lishimin", "tang", 4)
local ceju = fk.CreateViewAsSkill{
  name = "rfenghou__ceju",
  pattern = "slash,jink",
  prompt = function (self)
    if Self:getMark(self.name) == 0 then
      return "#rfenghou__ceju"
    else
      return "#rfenghou__ceju_"..Self:getMark(self.name)
    end
  end,
  interaction = function(self)
    local all_names = {"slash", "jink"}
    table.removeOne(all_names, Self:getMark(self.name))
    local names = U.getViewAsCardNames(Self, self.name, all_names)
    if #names > 0 then
      return U.CardNameBox {choices = names, all_choices = all_names}
    end
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    room:setPlayerMark(player, self.name, 0)
    local equip = table.find(player:getCardIds("hej"), function (id)
      return Fk:getCardById(id).type == Card.TypeEquip
    end)
    local trick = table.find(player:getCardIds("hej"), function (id)
      return Fk:getCardById(id).type == Card.TypeTrick
    end)
    local targets = table.filter(room.alive_players, function (p)
      if #p:getCardIds("e") > 0 and equip then
        return true
      end
      if #p:getCardIds("j") > 0 and trick then
        return true
      end
    end)
    local prompt, flag = "#rfenghou__ceju-choose:::"..use.card.name, "ej"
    if not equip then
      prompt, flag = "#rfenghou__ceju_trick-choose:::"..use.card.name, "j"
    end
    if not trick then
      prompt, flag = "#rfenghou__ceju_equip-choose:::"..use.card.name, "e"
    end
    local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, prompt, self.name, false)
    to = room:getPlayerById(to[1])
    if to ~= player then
      room:setPlayerMark(player, self.name, use.card.name)
    end
    local card = #to:getCardIds(flag) == 1 and to:getCardIds(flag) or room:askForCardChosen(player, to, flag, self.name)
    room:throwCard(card, self.name, to, player)
  end,
  enabled_at_play = function (self, player)
    if player:getMark(self.name) == "slash" then return end
    return table.find(Fk:currentRoom().alive_players, function (p)
      if #p:getCardIds("e") > 0 and table.find(player:getCardIds("hej"), function (id)
        return Fk:getCardById(id).type == Card.TypeEquip
      end) then
        return true
      end
      if #p:getCardIds("j") > 0 and table.find(player:getCardIds("hej"), function (id)
        return Fk:getCardById(id).type == Card.TypeTrick
      end) then
        return true
      end
    end)
  end,
  enabled_at_response = function (self, player, response)
    if response then return end
    if table.find(Fk:currentRoom().alive_players, function (p)
      if #p:getCardIds("e") > 0 and table.find(player:getCardIds("hej"), function (id)
        return Fk:getCardById(id).type == Card.TypeEquip
      end) then
        return true
      end
      if #p:getCardIds("j") > 0 and table.find(player:getCardIds("hej"), function (id)
        return Fk:getCardById(id).type == Card.TypeTrick
      end) then
        return true
      end
    end) then
      for _, name in ipairs({"slash", "jink"}) do
        if player:getMark(self.name) ~= name then
          local card = Fk:cloneCard(name)
          card.skillName = self.name
          if (Fk.currentResponsePattern == nil and player:canUse(card)) or
            (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
            return true
          end
        end
      end
    end
  end,
}
local zhiwen = fk.CreateActiveSkill{
  name = "rfenghou__zhiwen",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#rfenghou__zhiwen",
  can_use = function(self, player)
    if player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng() then
      local suits = {}
      for _, id in ipairs(Fk:currentRoom():getBanner("@$CenterArea")) do
        table.insertIfNeed(suits, Fk:getCardById(id).suit)
      end
      table.removeOne(suits, Card.NoSuit)
      return #suits == 4
    end
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:drawCards(player:getHandcardNum(), self.name)
  end,
}
local shisheng = fk.CreateTriggerSkill{
  name = "rfenghou__shisheng$",
}
zhiwen.CenterArea = true
lishimin:addSkill(ceju)
lishimin:addSkill(zhiwen)
lishimin:addSkill(shisheng)
Fk:loadTranslationTable{
  ["rfenghou__lishimin"] = "李世民",
  ["#rfenghou__lishimin"] = "帝范今古",
  ["designer:rfenghou__lishimin"] = "凡野",
  ["illustrator:rfenghou__lishimin"] = "NoTwoever",

  ["rfenghou__ceju"] = "策局",
  [":rfenghou__ceju"] = "你可以弃置场上一张你区域内有相同类别的牌，视为使用一张【杀】或【闪】，若弃置的牌属于其他角色，你下一次仅能发动另一项。",
  ["rfenghou__zhiwen"] = "治文",
  [":rfenghou__zhiwen"] = "出牌阶段限一次，若中央区花色齐全，你可以摸手牌数张牌。",
  ["rfenghou__shisheng"] = "始盛",
  [":rfenghou__shisheng"] = "主公技。",
  ["#rfenghou__ceju"] = "策局：你可以视为使用【杀】或【闪】，弃置场上一张你区域内有相同类别的牌",
  ["#rfenghou__ceju_slash"] = "策局：你可以视为使用【闪】，弃置场上一张你区域内有相同类别的牌",
  ["#rfenghou__ceju_jink"] = "策局：你可以视为使用【杀】，弃置场上一张你区域内有相同类别的牌",
  ["#rfenghou__ceju-choose"] = "策局：弃置场上一张装备牌或锦囊牌，若不为你的牌则下次不能转化【%arg】",
  ["#rfenghou__ceju_trick-choose"] = "策局：弃置场上一张锦囊牌，若不为你的牌则下次不能转化【%arg】",
  ["#rfenghou__ceju_equip-choose"] = "策局：弃置场上一张装备牌，若不为你的牌则下次不能转化【%arg】",
  ["#rfenghou__zhiwen"] = "治文：你可以摸手牌数张牌",
}

local licongke = General(extension, "rfenghou__licongke", "tang", 4)
local xunge = fk.CreateActiveSkill{
  name = "rfenghou__xunge",
  anim_type = "offensive",
  prompt = "#rfenghou__xunge",
  min_card_num = 0,
  target_num = 0,
  interaction = function(self)
    local choices = {"rfenghou__xunge_recast"}
    if #table.filter(Fk:currentRoom().discard_pile, function (id)
      return Fk:getCardById(id).trueName == "slash"
    end) > 5 then
      table.insert(choices, "rfenghou__xunge_draw")
    end
    if #Self:getPile(self.name) > 17 then
      table.insert(choices, "rfenghou__xunge_discard")
    end
    return UI.ComboBox { choices = choices, all_choices = {
      "rfenghou__xunge_recast",
      "rfenghou__xunge_draw",
      "rfenghou__xunge_discard",
    } }
  end,
  can_use = Util.TrueFunc,
  card_filter = function (self, to_select, selected)
    if self.interaction.data == "rfenghou__xunge_recast" then
      return Fk:getCardById(to_select).trueName == "slash"
    else
      return false
    end
  end,
  feasible = function (self, selected, selected_cards)
    if self.interaction.data == "rfenghou__xunge_recast" then
      return #selected_cards > 0
    else
      return #selected_cards == 0
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    if self.interaction.data == "rfenghou__xunge_recast" then
      room:recastCard(effect.cards, player, self.name)
    elseif self.interaction.data == "rfenghou__xunge_draw" then
      local cards = table.filter(room.discard_pile, function (id)
        return Fk:getCardById(id).trueName == "slash"
      end)
      player:addToPile(self.name, table.random(cards, 6), true, self.name, player.id)
      if not player.dead then
        player:drawCards(3, self.name)
      end
    elseif self.interaction.data == "rfenghou__xunge_discard" then
      local cards = table.random(player:getPile(self.name), 18)
      local moves = {}
      for i = 1, 18, 1 do
        table.insert(moves, {
          ids = {cards[i]},
          from = player.id,
          toArea = Card.DrawPile,
          moveReason = fk.ReasonJustMove,
          skillName = self.name,
          drawPilePosition = math.random(#room.draw_pile),
        })
      end
      room:moveCards(table.unpack(moves))
      if player.dead then return end
      local n = 9
      while n > 0 and not player.dead do
        local targets = table.filter(room.alive_players, function (p)
          return #p:getCardIds("ej") > 0
        end)
        if table.find(player:getCardIds("h"), function (id)
          return not player:prohibitDiscard(id)
        end) then
          table.insertIfNeed(targets, player)
        end
        if #targets == 0 then return end
        local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
          "#rfenghou__xunge-choose:::"..n, self.name, false)
          to = room:getPlayerById(to[1])
        if to == player then
          local all_cards = table.filter(player:getCardIds("hej"), function (id)
            return not player:prohibitDiscard(id)
          end)
          cards = room:askForCard(player, 1, n, true, self.name, false, tostring(Exppattern{ id = all_cards }),
            "#rfenghou__xunge-discard::"..to.id..":"..n, player:getCardIds("j"))
        else
          cards = room:askForCardsChosen(player, to, 1, n, "ej", self.name, "#rfenghou__xunge-discard::"..to.id..":"..n)
        end
        n = n - #cards
        room:throwCard(cards, self.name, to, player)
      end
    end
  end,

  on_acquire = function (self, player, is_start)
    player.room:handleAddLoseSkills(player, "rfenghou__xunge&", nil, false, true)
  end,
  on_lose = function (self, player, is_death)
    player.room:handleAddLoseSkills(player, "-rfenghou__xunge&", nil, false, true)
  end,
}
local xunge_viewas = fk.CreateViewAsSkill{
  name = "rfenghou__xunge&",
  pattern = "slash",
  prompt = "#rfenghou__xunge&",
  expand_pile = function(self)
    return table.filter(Fk:currentRoom():getBanner("@$CenterArea"), function (id)
      return Fk:getCardById(id).trueName == "slash"
    end)
  end,
  card_filter = function(self, to_select, selected)
    return #selected < 2 and table.contains(Fk:currentRoom():getBanner("@$CenterArea"), to_select)
  end,
  view_as = function(self, cards)
    if #cards ~= 2 then return end
    local card = Fk:cloneCard("slash")
    card.skillName = "rfenghou__xunge"
    self.cost_data = cards
    return card
  end,
  before_use = function (self, player, use)
    HQ.RemoveCenterCards(player, self.cost_data)
  end,
}
local xunge_prohibit = fk.CreateProhibitSkill{
  name = "#rfenghou__xunge_prohibit",
  prohibit_use = function(self, player, card)
    return player:hasSkill(xunge) and player.phase == Player.Play and card and card.trueName == "slash" and
      not card:isVirtual()
  end
}
local fenru = fk.CreateTriggerSkill{
  name = "rfenghou__fenru$",
  anim_type = "offensive",
  events = {fk.Deathed},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.damage and data.damage.from and data.damage.from == player
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    target.role = "renegade"
    room:broadcastProperty(target, "role")
  end,
}
xunge.CenterArea = true
Fk:addSkill(xunge_viewas)
xunge:addRelatedSkill(xunge_prohibit)
licongke:addSkill(xunge)
licongke:addSkill(fenru)
Fk:loadTranslationTable{
  ["rfenghou__licongke"] = "李从珂",
  ["#rfenghou__licongke"] = "",
  ["designer:rfenghou__licongke"] = "秀丽",
  ["illustrator:rfenghou__licongke"] = "乱世逐鹿",

  ["rfenghou__xunge"] = "寻戈",
  [":rfenghou__xunge"] = "出牌阶段，你的【杀】能且仅能重铸；你可以移去中央区两张【杀】视为使用一张【杀】；你可以将弃牌堆六张【杀】移出游戏并"..
  "摸三张牌；你可以将被移出游戏的十八张【杀】洗入牌堆再弃置你手牌区与场上共九张牌。",
  ["rfenghou__xunge&"] = "寻戈",
  [":rfenghou__xunge&"] = "你可以移去中央区两张【杀】，视为使用一张【杀】。",
  ["rfenghou__fenru"] = "焚如",
  [":rfenghou__fenru"] = "主公技，你杀死角色后，其本局游戏无法获胜！",
  ["#rfenghou__xunge&"] = "寻戈：你可以移去中央区两张【杀】，视为使用一张【杀】",
  ["#rfenghou__xunge"] = "寻戈：执行一项",
  ["rfenghou__xunge_recast"] = "重铸【杀】",
  ["rfenghou__xunge_draw"] = "移除弃牌堆的六张【杀】，摸三张牌",
  ["rfenghou__xunge_discard"] = "被移除的十八张【杀】洗入牌堆，弃置你手牌区与场上共九张牌",
  ["#rfenghou__xunge-choose"] = "寻戈：弃置你手牌区与场上的牌（共9张，还剩%arg张！）",
  ["#rfenghou__xunge-discard"] = "寻戈：弃置 %dest 至多%arg张牌",
}

return extension
